﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OpenQuarters.WebQuarters.Core
{
    public class ApplicationItem
    {
        public static T GetItem<T>(string key, Func<T> defaultValue)
        {
            if (!key.StartsWith("__") && !key.EndsWith("_expiry"))
            {
                DateTime? expiryDate = GetItem<DateTime?>("__" + key + "_expiry", () => null);
                if (expiryDate != null && expiryDate.Value <= DateTime.Now)
                {
                    Oracle.Session[key] = null;
                }
            }
            if (Oracle.Context.Application[key] == null)
            {
                Oracle.Context.Application[key] = defaultValue();
            }
            return (T)Oracle.Context.Application[key];
        }

        public static void SetItem<T>(string key, T value)
        {
            SetItem<T>(key, value, -1);
        }

        public static void SetItem<T>(string key, T value, int expiryMinutes)
        {
            Oracle.Context.Application[key] = value;
            if (expiryMinutes > -1)
            {
                SetItem<DateTime?>("__" + key + "_expiry", DateTime.Now.AddMinutes(expiryMinutes), -1);
            }
        }
    }
}
